/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package org.dromara.setting.init;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.utils.EnumUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.setting.domain.bo.SettingConfigGroupBo;
import org.dromara.setting.domain.bo.SettingConfigItemBo;
import org.dromara.setting.domain.vo.SettingConfigGroupVo;
import org.dromara.setting.domain.vo.SettingConfigItemVo;
import org.dromara.setting.enums.BastSettingEnums;
import org.dromara.setting.enums.SettingAllEnums;
import org.dromara.setting.service.ISettingConfigGroupService;
import org.dromara.setting.service.ISettingConfigItemService;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.service.ISysTenantService;
import org.ehcache.impl.internal.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 初始化系统配置
 *
 * @author heyi
 * 2024/8/10
 */
@Slf4j
@Service
public class InitSettingService {

    @Autowired
    private ISettingConfigGroupService groupService;
    @Autowired
    private ISettingConfigItemService iSettingConfigItemService;
    @Autowired
    private ScheduledExecutorService scheduledExecutorService;
    @Autowired
    private ISysTenantService sysTenantService;
    private static Set<BastSettingEnums> allEnums = new HashSet<>();
    @PostConstruct
    public void init() {
        allEnums = EnumUtils.getAllEnumsValue(SettingAllEnums.class);
        // 检查所有租户的配置信息
        scheduledExecutorService.execute(() -> {
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageNum(1);
            pageQuery.setPageSize(100);
            SysTenantBo query = new SysTenantBo().setStatus(Constants.SUCCESS);
            TableDataInfo<SysTenantVo> tableDataInfo = sysTenantService.queryPageList(query, pageQuery);
            while (CollUtil.isNotEmpty(tableDataInfo.getRows())) {
                tableDataInfo.getRows().forEach(item -> {
                    String tenantId = item.getTenantId();
                    initSetting(tenantId);
                });
                pageQuery.setPageNum(pageQuery.getPageNum() + 1);
                tableDataInfo = sysTenantService.queryPageList(query, pageQuery);
            }
        });
    }

    public void initSetting(String tenantId) {
        log.info("initSetting start");
        Map<String, SettingConfigGroupVo> cache = new ConcurrentHashMap<>();
        allEnums.stream().parallel().forEach(item -> {
            TenantHelper.dynamic(tenantId, () -> {
                String groupType = item.getGroupType();
                SettingConfigGroupVo settingConfigGroupVo = cache.get(groupType);
                if (settingConfigGroupVo == null) {
                    settingConfigGroupVo = groupService.queryByType(groupType);
                    cache.put(groupType, settingConfigGroupVo);
                }
                if (ObjectUtil.isNull(settingConfigGroupVo)) {
                    SettingConfigGroupBo add = new SettingConfigGroupBo();
                    add.setName(item.getName());
                    add.setType(groupType);
                    groupService.insertByBo(add);
                    Long groupId = add.getId();
                    SettingConfigItemBo itemAdd = new SettingConfigItemBo();
                    itemAdd.setConfigGroupId(groupId);
                    itemAdd.setName(item.getKeyDesc());
                    itemAdd.setKey(item.getKey());
                    itemAdd.setValue(item.getDefaultValue());
                    itemAdd.setValueInputType(item.getValueInputType());
                    itemAdd.setRemark(item.getRemark());
                    iSettingConfigItemService.insertByBo(itemAdd);
                } else {
                    Long groupId = settingConfigGroupVo.getId();
                    SettingConfigItemVo settingConfigItemVo = iSettingConfigItemService.queryByGroupIdAndKey(groupId, item.getKey());
                    if (ObjectUtil.isNull(settingConfigItemVo)) {
                        SettingConfigItemBo itemAdd = new SettingConfigItemBo();
                        itemAdd.setConfigGroupId(groupId);
                        itemAdd.setName(item.getKeyDesc());
                        itemAdd.setKey(item.getKey());
                        itemAdd.setValueInputType(item.getValueInputType());
                        itemAdd.setRemark(item.getRemark());
                        itemAdd.setValue(item.getDefaultValue());
                        iSettingConfigItemService.insertByBo(itemAdd);
                    } else {
                        SettingConfigItemBo update = new SettingConfigItemBo();
                        update.setId(settingConfigItemVo.getId());
                        update.setConfigGroupId(groupId);
                        update.setName(item.getKeyDesc());
                        update.setKey(item.getKey());
                        update.setValueInputType(item.getValueInputType());
                        update.setRemark(item.getRemark());
                        if (StrUtil.isBlank(settingConfigItemVo.getValue())) {
                            update.setValue(item.getDefaultValue());
                        }
                        iSettingConfigItemService.updateByBo(update);
                    }
                }
            });
        });
    }
}
